import { lazyReportBatch } from "../report";

export default function observerLCP() {
  const entryHandler = (list) => {
    if (observer) {
      observer.disconnect();
    }
    for (const entry of list.getEntries()) {
      const json = entry.toJSON();
      console.log("Largest Contentful Paint:", json);
      //   上报
      const reportData = {
        ...json,
        type: "performance",
        subType: entry.name,
        pageUrl: window.location.href,
      };
      lazyReportBatch(reportData);
    }
  };

  // 统计和计算FCP( First Content Paint) 的性能指标
  const observer = new PerformanceObserver(entryHandler);

  // buffered:true 确保在页面加载时也能捕获到之前的绘制事件
  observer.observe({
    type: "largest-contentful-paint",
    buffered: true,
  });
}
